﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Text;
using Newtonsoft.Json;
using System.Runtime.Serialization;

namespace Utility.DataSystem
{
	[JsonObject (MemberSerialization = MemberSerialization.OptIn)]
	public class DataStorage : IFieldSource
	{
		[JsonProperty]
		Dictionary<string, DataValue> dict = new Dictionary<string, DataValue> ();

		public DataStorage ()
		{
		}

		public DataStorage (string name)
		{
			Name = name;
		}

		public string Name { get; private set; } = "DataStorage";

		DataValue IFieldSource.GetData (IDataFieldContext context, FieldQuery fieldQuery, out bool isInterested)
		{
			isInterested = true;
			return this[fieldQuery.Setting];
		}

		public DataValue this[string key]
		{
			get => dict.TryGetValue (key);
			set => dict[key] = value;
		}

		public DataValue this[DataFieldSetting fieldSetting]
		{
			get => dict.TryGetValue (fieldSetting.Key);
			set => dict[fieldSetting.Key] = value;
		}

		public void Remove (string key) => dict.Remove (key);

		public void CombineData (DataFieldSetting field, DataValue data)
		{
			var val = dict.TryGetValue (field.Key);
			dict[field.Key] = field.CombineValue (val, data);
		}

		public void CombineData (string key, DataValue data)
		{
			var field = FieldCenter.GetField (key);
			if (field == null)
			{
				throw new Exception ($"cannot find field: {field}");
			}
			CombineData (field, data);
		}

		public void Clear ()
		{
			dict.Clear ();
		}
	}

}